package com.jame.basics.thread.juc;

/**
 * @author : Jame
 * @date : 2021-01-10 16:16
 **/
public class LockTest {
    public static void main(String[] args) {
        Calculate calculate = new Calculate();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    calculate.add();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    calculate.reduce();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();    new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    calculate.add();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "C").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    calculate.reduce();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "D").start();

    }
}

class Calculate {
    int i = 0;

    //增加方法
    public synchronized void add() throws InterruptedException {
        //if判断会出现虚假唤醒,wait等待后被唤醒会直接走出if执行下面代码,而while会重复判断
        while (i != 0) {
            //需要等待
            this.wait();
        }
        //增加
        i++;
        System.out.println(Thread.currentThread().getName() + "==" + i);
        //唤醒其他线程
        this.notifyAll();


    }

    //减少方法
    public synchronized void reduce() throws InterruptedException {
        while (i == 0) {
            this.wait();
        }
        i--;
        System.out.println(Thread.currentThread().getName() + "==" + i);
        this.notifyAll();
    }

}
